<?php

namespace App\Console\Commands\Admin;

use Illuminate\Console\Command;

class ServiceMaker extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'admin:make-service {serviceName} {path=Admin}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '创建service类';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $serviceName = $this->argument('serviceName');
        $subPath = $this->argument('path');
        // dd($subPath);

        $this->createService($serviceName, $subPath);

        $this->info("Service created successfully!");
    }


    /**
     * Create the service file.
     *
     * @param string $serviceName
     * @return void
     */
    protected function createService($serviceName, $path)
    {
        $servicePath = app_path("Modules/{$path}/Services/{$serviceName}Service.php");

        if (file_exists($servicePath)) {
            $this->error("Service already exists!");
            return;
        }

        $stub = $this->getStub();
        // Define replacements
        $replacements = [
            'class' => $serviceName,
            'path' => $path,
            // Add more replacements as needed
        ];
        $this->replaceVariables($stub, $replacements);

        file_put_contents($servicePath, $stub);

        $this->info("Service created: {$servicePath}");
    }

    /**
     * Get the service stub file.
     *
     * @return string
     */
    protected function getStub()
    {
        return file_get_contents(resource_path('stubs/service.stub'));
    }

    /**
     * Replace the class name in the stub.
     *
     * @param string $stub
     * @param string $className
     * @return string
     */
    protected function replaceVariables(&$stub, $replacements)
    {
        foreach ($replacements as $search => $replace) {
            $stub = str_replace("{{{$search}}}", $replace, $stub);
        }

        return $stub;
    }
}
